package com.hontech.bread.ui.dialog


import android.view.ViewGroup.LayoutParams
import android.widget.Button
import android.widget.DatePicker
import com.hontech.bread.R
import kotlinx.coroutines.CompletableDeferred
import java.util.Calendar

class DateTime(
    val year: Int,
    val month: Int,
    val date: Int,
    val hour: Int,
    val minute: Int,
) {


    fun timestamp(): Long {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.YEAR, year)
        calendar.set(Calendar.MONTH, month - 1)
        calendar.set(Calendar.DAY_OF_MONTH, date)
        calendar.set(Calendar.HOUR, hour)
        calendar.set(Calendar.MINUTE, minute)
        calendar.set(Calendar.SECOND, 0)
        return calendar.timeInMillis / 1000
    }

    fun format(): String {
        return "${year}-${month}-${date}"
    }
}

private class DateTimeSelectDialog : DraggableWindow(
    LayoutParams.MATCH_PARENT,
    LayoutParams.WRAP_CONTENT,
    R.layout.dialog_date_time_select,
    false
) {

    private val mDatePicker = view.findViewById<DatePicker>(R.id.id_time_date_picker)
    private val mBtnConfirm = view.findViewById<Button>(R.id.id_time_btn_confirm)


    suspend fun select(): DateTime {
        showCenter()

        val promise = CompletableDeferred<Unit>()
        mBtnConfirm.setOnClickListener { promise.complete(Unit) }
        promise.await()

        val year = mDatePicker.year
        val month = mDatePicker.month + 1
        val day = mDatePicker.dayOfMonth
        val dt = DateTime(year, month, day, 0, 0)
        dismiss()
        return dt
    }

}

suspend fun selectDateTime(): DateTime {
    return DateTimeSelectDialog().select()
}
